﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace UnvApi
{
    public class UnvVmsManager
    {
        //宇视vms系统地址、账号信息
        private static readonly string SERVER_URL = "http://172.20.96.210";
        private static readonly string USERNAME = "admin";
        private static readonly string PASSWORD = "********";

        /// <summary>
        /// 基础请求方法
        /// </summary>
        /// <param name="path">请求路径</param>
        /// <param name="method">使用的HTTP方法</param>
        /// <param name="requestBody">请求体</param>
        /// <returns>宇视vms平台原始response</returns>
        public static async Task<string> sendRequestAsync(string path, string method, string requestBody)
        {
            string response = await UnvHttpMethods.sendMessageAsync(SERVER_URL + path, USERNAME, PASSWORD, method, requestBody);
            return response;
        }
        /// <summary>
        /// 获取宇视平台内所有部门信息
        /// </summary>
        /// <returns>示例（PID为该部门归属部门的ID）：[{"PID":1,"ID":25,"Name":"技术部"},{"PID":0,"ID":1,"Name":"宝信软件"}]</returns>
        public static async Task<string> getDepartments()
        {
            string requestPath = "/LAPI/V1.0/System/Org/OrgList?Type=6";
            string requestBody = "{\"Limit\":200,\"Offset\":0,\"Num\":0}";
            string response = await sendRequestAsync(requestPath, "GET", requestBody);
            return response;
        }
        /// <summary>
        /// 查询人员列表（默认查询3-总集合，前200条）
        /// </summary>
        /// <returns></returns>
        public static async Task<string> queryPerson()
        {
            //默认deptId=3-总集合
            string response = await queryPerson(3);
            return response;
        }
        /// <summary>
        /// 根据部门id查询人员列表（部门id通过getDepartments获取）
        /// </summary>
        /// <param name="deptId">部门id</param>
        /// <returns></returns>
        public static async Task<string> queryPerson(int deptId)
        {
            //默认deptId=3-总集合
            string response = await queryPerson(deptId, 200, 0);
            return response;
        }
        /// <summary>
        /// 根据部门id查询人员列表，带查询条数限制和偏移量（部门id通过getDepartments获取）
        /// </summary>
        /// <param name="deptId">部门id</param>
        /// <param name="limit">查询条数限制，最高200</param>
        /// <param name="offset">查询序号偏移量</param>
        /// <returns></returns>
        public static async Task<string> queryPerson(int deptId, int limit, int offset)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People/Info";
            string requestBody = "{\"Num\":2,\"QueryInfos\":[" +
                "{\"QryType\":30,\"QryCondition\":0,\"QryData\":" + deptId + "}," +
                "{\"QryType\":28,\"QryCondition\":0,\"QryData\":0}" +
                "],\"Limit\":"+limit+",\"Offset\":"+offset+"}";
            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;
        }
        /// <summary>
        /// 根据姓名、工号查询人员（若只需要传入其中一个查询条件，则另一个传入空字符串""即可）
        /// </summary>
        /// <param name="name">姓名（可为空字符串""）</param>
        /// <param name="id">工号（可为空字符串""）</param>
        /// <returns></returns>
        public static async Task<string> queryPerson(string name, string id)
        {
            string response = await queryPerson(3, name, id);
            return response;
        }
        /// <summary>
        /// 限定部门，然后根据姓名、工号查询人员
        /// </summary>
        /// <param name="deptId">部门id（通过getDepartments获取）</param>
        /// <param name="name">姓名（可为空字符串""）</param>
        /// <param name="id">工号（可为空字符串""）</param>
        /// <returns></returns>
        public static async Task<string> queryPerson(int deptId, string name, string id)
        {
            string response = await queryPerson(deptId, name, id, 200, 0);
            return response;

        }
        /// <summary>
        /// 限定部门，然后根据姓名、工号查询人员，并设置查询条数限制和偏移量
        /// </summary>
        /// <param name="deptId">部门id（通过getDepartments获取）</param>
        /// <param name="name">姓名（可为空字符串""）</param>
        /// <param name="id">工号（可为空字符串""）</param>
        /// <param name="limit">查询条数限制，最大为200</param>
        /// <param name="offset">查询序号偏移量</param>
        /// <returns></returns>
        public static async Task<string> queryPerson(int deptId, string name, string id, int limit, int offset)
        {
            int num = 2;
            string conditions = "{\"QryType\":30,\"QryCondition\":0,\"QryData\":" + deptId + "}," +
                "{\"QryType\":28,\"QryCondition\":0,\"QryData\":0}";
            if (name.Trim().Length > 0)
            {
                num++;
                conditions += ",{\"QryType\":55,\"QryCondition\":6,\"QryData\":\"" + name + "\"}";
            }
            if (id.Trim().Length > 0)
            {
                num++;
                conditions += ",{\"QryType\":58,\"QryCondition\":6,\"QryData\":\"173807\"}";
            }

            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People/Info";
            string requestBody = "{\"Num\":" + num + ",\"QueryInfos\":[" + conditions + "],\"Limit\":"+limit+",\"Offset\":"+offset+"}";
            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;

        }
        public static async Task<string> getPeronInfo(int PersonID)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/People/"+PersonID;
            string requestBody = "{}";
            string response = await sendRequestAsync(requestPath, "GET", requestBody);
            return response;
        }
        /// <summary>
        /// 获取授权列表(分组)信息
        /// </summary>
        /// <returns></returns>
        public static async Task<string> getPermissionList()
        {
            string requestPath = "/LAPI/V1.0/PACS/PermissionGroup/PermissionInfo";
            string requestBody = "{\"Num\":1,\"QueryInfoList\":[{\"QryType\":28,\"QryCondition\":0,\"QryData\":\"0\"}],\"Limit\":200,\"Offset\":0}";
            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;
        }
        /// <summary>
        /// 获取授权组详情信息
        /// </summary>
        /// <param name="id">授权组id，通过getPermissionList获取</param>
        /// <returns></returns>
        public static async Task<string> getPermissionInfo(string id)
        {
            string requestPath = "/LAPI/V1.0/PACS/PermissionGroup/" + id;
            string requestBody = "{}";
            string response = await sendRequestAsync(requestPath, "GET", requestBody);
            return response;
        }
        /// <summary>
        /// 获取设备列表
        /// </summary>
        /// <returns></returns>
        public static async Task<string> getEquipmentList()
        {
            string requestPath = "/LAPI/V1.0/PACS/Door/DetailInfos";
            string requestBody = "{}";
            string response = await sendRequestAsync(requestPath, "GET", requestBody);
            return response;
        }
        /// <summary>
        /// 查询通行记录（传入起止秒级时间戳）
        /// </summary>
        /// <param name="timestampStart">起始时间</param>
        /// <param name="timestampEnd">终止时间</param>
        /// <returns></returns>
        public static async Task<string> queryPassRecords(long timestampStart, long timestampEnd)
        {
            string response = await queryPassRecords(timestampStart, timestampEnd, 200, 0);
            return response;
        }
        /// <summary>
        /// 查询通行记录（传入起止秒级时间戳；单次查询限制条数；记录序号偏移量）
        /// </summary>
        /// <param name="timestampStart">起始时间</param>
        /// <param name="timestampEnd">终止时间</param>
        /// <param name="limit">单次查询限制条数</param>
        /// <param name="offset">记录序号偏移量</param>
        /// <returns></returns>
        public static async Task<string> queryPassRecords(long timestampStart, long timestampEnd, int limit, int offset)
        {
            string requestPath = "/LAPI/V1.0/PACS/AttendanceLogs";

            string requestBody = "{\"Num\":4,\"Limit\":" + limit + ",\"Offset\":" + offset + ",\"QueryInfos\":[{\"QryType\": 4,\"QryCondition\": 3,\"QryData\": \"" + timestampStart + "\"},{\"QryType\": 4,\"QryCondition\": 4,\"QryData\": \"" + timestampEnd + "\"},{\"QryType\": 28,\"QryCondition\": 0,\"QryData\": \"0\"},{\"QryType\": 4,\"QryCondition\": 9,\"QryData\": \"" + timestampEnd + "\"}]}";
            //string requestBody = "{\"Num\":5,\"Limit\":" + limit + ",\"Offset\":" + offset + ",\"QueryInfos\":[{\"QryType\": 50, \"QryCondition\": 0, \"QryData\": 1},{\"QryType\": 4,\"QryCondition\": 3,\"QryData\": \"" + timestampStart + "\"},{\"QryType\": 4,\"QryCondition\": 4,\"QryData\": \"" + timestampEnd + "\"},{\"QryType\": 28,\"QryCondition\": 0,\"QryData\": \"0\"},{\"QryType\": 4,\"QryCondition\": 9,\"QryData\": \"" + timestampEnd + "\"}]}";

            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;
        }
        /// <summary>
        /// 新增授权人员
        /// </summary>
        /// <param name="personInfo">人员信息类对象</param>
        /// <returns></returns>
        public static async Task<string> addPerson(PersonInfo personInfo)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People";

            var json = new
            {
                Num = 1,
                PersonInfoList = new[] {
                    personInfo
                }
            };
            string requestBody = UnvHttpMethods.generateJsonString(json);

            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;
        }
        /// <summary>
        /// 新增授权人员
        /// </summary>
        /// <param name="personInfoList">人员信息类对象数组</param>
        /// <returns></returns>
        public static async Task<string> addPerson(PersonInfo[] personInfoList)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People";

            var json = new
            {
                Num = personInfoList.Length,
                PersonInfoList = personInfoList
            };
            string requestBody = UnvHttpMethods.generateJsonString(json);

            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;
        }
        /// <summary>
        /// 更新授权人员信息（注意，传入的对象中的PersonID不能为空，且必须为实际存在的ID）
        /// </summary>
        /// <param name="personInfo">人员信息类对象数组</param>
        /// <returns></returns>
        public static async Task<string> updatePerson(PersonInfo personInfo)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People";

            var json = new
            {
                Num = 1,
                PersonInfoList = new[] {
                    personInfo
                }
            };
            string requestBody = UnvHttpMethods.generateJsonString(json);

            string response = await sendRequestAsync(requestPath, "PUT", requestBody);
            return response;
        }
        /// <summary>
        /// 根据宇视id删除人员
        /// </summary>
        /// <param name="personId">人员id</param>
        /// <returns></returns>
        public static async Task<string> deletePerson(int personId)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People";

            var json = new
            {
                PersonNum = 1,
                PersonIDList = new[] {
                    personId
                }
            };
            string requestBody = UnvHttpMethods.generateJsonString(json);

            string response = await sendRequestAsync(requestPath, "DELETE", requestBody);
            return response;
        }
        /// <summary>
        /// 批量删除人员信息
        /// </summary>
        /// <param name="personIdList">人员id列表</param>
        /// <returns></returns>
        public static async Task<string> deletePerson(int[] personIdList)
        {
            string requestPath = "/LAPI/V1.0/PeopleLibraries/0/People";

            var json = new
            {
                PersonNum = personIdList.Length,
                PersonIDList = personIdList
            };
            string requestBody = UnvHttpMethods.generateJsonString(json);

            string response = await sendRequestAsync(requestPath, "DELETE", requestBody);
            return response;
        }
        public static async Task<string> addPermissionGroup(PermissionInfo permissionInfo)
        {
            string requestPath = "/LAPI/V1.0/PACS/PermissionGroup";

            string requestBody = UnvHttpMethods.generateJsonString(permissionInfo);

            string response = await sendRequestAsync(requestPath, "POST", requestBody);
            return response;
        }
        public static async Task<string> updatePermissionGroup(PermissionInfo permissionInfo)
        {
            string requestPath = "/LAPI/V1.0/PACS/PermissionGroup/" + permissionInfo.PermissionID;

            string requestBody = UnvHttpMethods.generateJsonString(permissionInfo);

            string response = await sendRequestAsync(requestPath, "PUT", requestBody);
            return response;
        }
        public static async Task<string> deletePermissionGroup(int[] idList)
        {
            string requestPath = "/LAPI/V1.0/PACS/PermissionGroup";

            var json = new
            {
                Num = idList.Length,
                IDList = idList
            };
            string requestBody = UnvHttpMethods.generateJsonString(json);

            string response = await sendRequestAsync(requestPath, "DELETE", requestBody);
            return response;
        }
    }
}
